<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');


/**
 * YekComputer (r) CMS controller class
 * 
 * @version: 1.0
 * @copyright (c) 2009, YekComputer. All rights reserved.
 * @author Babak Taraghi 'babak.taraghi@gmail.com'
 * @license Code licensed under the BSD License.
 */
class Home extends CI_Controller {
	
	
	/**
	 * @desc Array - datas which should pass to the views
	 */
	var $data = array();
	
	
	
	/**
	 * @desc String - Categories model name
	 */
	var $categoriesModelName = "categoriesModel";
	
	
	
	/**
	 * @desc Controller Constructor
	 * This will check the session to see if the user is logged in or what
	 * And will load the related language files
	 */
	function Home(){

		parent::__construct();
		if(!$this->session->userdata('cploggedin')){
			redirect("cp/users");
		}
		
		// language
		$this->lang->load("common");
		$this->lang->load("cp");
		
		$this->data["title"] = $this->lang->line("cpTitle");
		$this->data["breadcrumb"] = array($this->lang->line("home")=>base_url()."cp");
		
		$this->load->model("accessLevelModel");
		
		$this->data["contactsModuleAL"] = $this->accessLevelModel->getRecords(array("module_name"=>"contactsModule","category_id"=>$this->session->userdata["category_id"]));
		$this->data["articlesModuleAL"] = $this->accessLevelModel->getRecords(array("module_name"=>"articlesModule","category_id"=>$this->session->userdata["category_id"]));
		$this->data["cpusersModuleAL"] = $this->accessLevelModel->getRecords(array("module_name"=>"cpusersModule","category_id"=>$this->session->userdata["category_id"]));
		$this->data["pagesModuleAL"] = $this->accessLevelModel->getRecords(array("module_name"=>"pagesModule","category_id"=>$this->session->userdata["category_id"]));
		$this->data["productsModuleAL"] = $this->accessLevelModel->getRecords(array("module_name"=>"productsModule","category_id"=>$this->session->userdata["category_id"]));
		
	}
	
	
	
	
	/**
	 * @desc This will get called when no method specified 
	 * Will show a welcome page
	 */
	function index(){
		$this->data["moduleName"] = "";
		$this->data["title"] .= " - ".$this->lang->line("home");
		$this->data["content"] = $this->load->view("cp/home",$this->data,TRUE);
		
		// check to see if the request is ajax based or not
		if($this->input->is_ajax_request()){
			
			$i=0;
			$breadCrumb = "";
			foreach($this->data["breadcrumb"] as $bread=>$crumb){
				if(++$i > 1) $breadCrumb .= "&nbsp;&raquo;&nbsp;";
				if($crumb != ""){
					$breadCrumb .= "<a href=".$crumb." onclick=\"one.changeContent(this.href); return false;\">";
				}
				$breadCrumb .= $bread;
				if($crumb != ""){
					$breadCrumb .= "</a>";
				}
			}
			$json = "{";
			$json .= "breadCrumb:'".$breadCrumb."',";
			$json .= "title:'".$this->data["title"]."'";
			$json .= "}";
			echo $json."|-|".$this->data["content"];
		}else{
			$this->load->view('cp/container',$this->data);
		}
		
	}
	
	
	
	
	/**
	 * @desc This is the inventory method 
	 * Will show a list and create pagination links
	 * @param String 'modelName'
	 * @param Integer 'from' idicates the start record used for paging
	 * @param $_POST 'keyword' will be searched using 'or like' query in all fields of table exept "private","category_id","insert_time","confirmation_status"
	 */
	function inventory($modelName,$from=0){
		
		// loading models,language
		$this->load->model($modelName);
		$this->load->helper('text');
		
		$this->lang->load($this->$modelName->langFileName);
		
		$this->load->helper("form");
		
		if(!isset($this->$modelName->listControllerName))
			$this->data["listControllerName"] = "home";
		else
			$this->data["listControllerName"] = $this->$modelName->listControllerName;
		
		
		// we will use these in view
		$this->data["modelName"] = $modelName;
		$this->data["moduleName"] = $this->$modelName->moduleName;
		$this->data["breadcrumb"][$this->lang->line($this->$modelName->moduleName)] = base_url()."cp/".$this->data["listControllerName"]."/inventory/".$modelName;
		
		if($this->input->post("keyword")){
			$this->data["title"] .= " - ".$this->lang->line("search");
			$this->data["breadcrumb"][$this->lang->line("search")] = "";
		}else{
			$this->data["breadcrumb"][$this->lang->line("list")] = "";
			$this->data["title"] .= " - ".$this->lang->line("list")." ".$this->lang->line($this->$modelName->moduleName);
		}
		
		$accessLevelRecs = $this->accessLevelModel->getRecords(array("module_name"=>$this->$modelName->moduleName."Module","category_id"=>$this->session->userdata["category_id"]));
		
		if(count($accessLevelRecs) > 0)$accessLevel = $accessLevelRecs[0];
		else $accessLevel = null;
		
		if(count($accessLevelRecs) < 1 || !$accessLevel->perm_view){
			
			$this->data["errors"][] = $this->lang->line("no-perm");
			$this->data["content"] = $this->load->view("cp/messages",$this->data,TRUE);
		
		}else{

			// list orders
			$this->data["sortBy"] = "id";
			$this->data["sortType"] = "desc";
			if($this->input->cookie("listsorder")){
				$cookieValue = $this->input->cookie("listsorder");
				$orders = explode(";",$cookieValue);
				foreach($orders as $order){
					$order = explode("-",$order);
					if($order[0] == $this->$modelName->moduleName."|".$modelName){
						$this->data["sortBy"] = $order[1];
						$this->data["sortType"] = $order[2];
					}
				}
			}
			
			$rows = array();
			
			// check if this is a search request or a simple list
			if($this->input->post("keyword")){
				$where = array();
				$fields = $this->$modelName->listFields;
				foreach($fields as $field=>$specifications){
					if($specifications["searchable"] && $field != "noSelect" && $field != "noDelete" && $field != "noSearch"){
						if($specifications["type"] == "refrenceID"){
	
							// bad bad, i will make it look better
							// trying to fetch record of other table thats like keyword
							$specifiedModelName = $specifications["modelName"];
							$this->load->model($specifiedModelName);
							$rr = $this->$specifiedModelName->searchRecords(array($specifications["titleField"]=>$this->input->post("keyword")),0,0);
							
							if(count($rr) > 0)
								$where[$field] = $rr[0]->id;
							
						}elseif($specifications["type"] == "categoryRefrenceID"){
							
							$specifiedModelName = $this->categoriesModelName;
							$this->load->model($specifiedModelName);
							$rr = $this->$specifiedModelName->searchLangs($this->input->post("keyword"));
							
							
							if(count($rr) > 0)
								$where[$field] = $rr[0]->cat_id;
							
						}else{
							$where[$field] = $this->input->post("keyword");
						}
					}
				}
				
				$total = $this->$modelName->getSearchedRecordsNumber($where);
				if($total > 100){
					$this->data["errors"][] = $this->lang->line("overflowSearchResults");
				}else{
					$rows = $this->$modelName->searchRecords($where,$from,100,$this->data["sortBy"],$this->data["sortType"]);
				}
			}else{
				$rows = $this->$modelName->getRecords("",$from,15,$this->data["sortBy"],$this->data["sortType"]);
				$total = $this->$modelName->getTotalRecordsNumber();
				$this->_setPagingLinks($total,15,5,"inventory/".$modelName);
			}
			
			// see if we got any thing to show or not
			if(count($rows) > 0){
				$this->data["rows"] = array();
				$this->load->helper("jdate");
				
				$listFields = $this->$modelName->listFields;
				
				// need to load specific models or helpers if there are any
				foreach($listFields as $listField=>$specifications){
					if($specifications["type"] == "refrenceID"){
						$specifiedModel = $specifications["modelName"];
						$this->load->model($specifiedModel);
					}
					if($specifications["type"] == "categoryRefrenceID"){
						$this->load->model("categoriesModel");
					}
					if($specifications["type"] == "thumb"){
						$this->load->helper("simple_image");
						$simpleImage = new SimpleImage();
					}
				}
				
				// iterating over rows
				foreach($rows as $row){
	
					foreach($listFields as $listField=>$specifications){
						if($specifications["type"] == "refrenceID"){
							$specifiedModel = $specifications["modelName"];
							$specifiedTitle = $specifications["titleField"];
							$specifiedRecord = $this->$specifiedModel->getRecord("id",$row->$listField);
							$row->$specifiedTitle = $specifiedRecord->$specifiedTitle;
						}
						if($specifications["type"] == "categoryRefrenceID"){
							$langRecord = $this->categoriesModel->getLangRecord($row->category_id,"en");
							if(is_object($langRecord))
								$row->category_id = $langRecord->title;
						}
						if($specifications["type"] == "refrence"){
							$row->$listField = $this->lang->line($row->$listField);
						}
						if($specifications["type"] == "thumb" && $row->$listField != ""){
							$row->$listField = $simpleImage->getThumbPathWidthHeight($row->$listField,0,50);
						}
						if($specifications["type"] == "time"){
							if($row->$listField > 1){
								
								$row->$listField = array(
									"date"=>@date("l d F Y",$row->$listField),
									"time"=>@date("H:i:s",$row->$listField)
								);
								
							}else{
								$row->$listField = array(
									"date"=>"",
									"time"=>""
								);
							}
						}
						/*if($specifications["type"] == "time"){
							if($row->$listField > 1){
								$row->jdate = @date("l, d F Y",$row->$listField);
								$row->date = @date("H:i:s",$row->$listField);
								
//								if(isset($row->language) && $row->language != "fa"){
//									$row->jdate = date("l d F Y",$row->$listField);
//									$row->date = jdate("l d F Y ساعت H:i:s",$row->$listField);
//								}else{
//									$row->jdate = jdate("l d F Y",$row->$listField);
//									$row->date = date("l d F Y ساعت H:i:s",$row->$listField);
//								}
							}else{
								$row->jdate = "";
								$row->date = "";
							}
						}*/
					}
					$this->data["rows"][] = $row;
				}
			}else{
				$this->data["messages"][] = $this->lang->line("noRecords");
			}
			
			// lets load the view
			if(isset($this->data["errors"]) || isset($this->data["messages"])){
				$this->data["content"] = $this->load->view("cp/messages",$this->data,TRUE);
			}else{
				$this->data["columns"] = $this->$modelName->listFields;
				$this->data["content"] = $this->load->view("cp/list",$this->data,TRUE);
			}
			
		}
		
		// check to see if the request is ajax based or not
		if($this->input->is_ajax_request()){
			
			$i=0;
			$breadCrumb = "";
			foreach($this->data["breadcrumb"] as $bread=>$crumb){
				if(++$i > 1) $breadCrumb .= "&nbsp;&raquo;&nbsp;";
				if($crumb != ""){
					$breadCrumb .= "<a href=".$crumb." onclick=\"one.changeContent(this.href); return false;\">";
				}
				$breadCrumb .= $bread;
				if($crumb != ""){
					$breadCrumb .= "</a>";
				}
			}
			$json = "{";
			$json .= "breadCrumb:'".$breadCrumb."',";
			$json .= "title:'".$this->data["title"]."'";
			$json .= "}";
			echo $json."|-|".$this->data["content"];
		}else{
			$this->load->view('cp/container',$this->data);
		}
		
	}
	
	
	
	
	/**
	 * @desc This will set pagination links html to the $this->data field.
	 * @param Integer 'totalRecs' is the number of total records of the table
	 * @param Integer 'recsPerPage' indicates how many of records of the table should list in a page
	 * @param Integer 'uriSegment' which part of url indicates page number
	 * @param String 'extraURL' the url (method and modelname)that should get called after a page clicked
	 */
	function _setPagingLinks($totalRecs,$recsPerPage,$uriSegment,$extraURL){
		$this->load->library('pagination');
		$c = array(
			'base_url'=>base_url()."cp/home/$extraURL",
			'total_rows'=> $totalRecs,
			'per_page'=> $recsPerPage,
			"uri_segment"=>$uriSegment,
			"num_links"=>3,
			"full_tag_open"=>"<center>",
			"full_tag_close"=>"</center>",
			"first_link"=>$this->lang->line("firstPage"),
			"first_tag_open"=>"<div class='firstPage'>",
			"first_tag_close"=>"</div>",
			"last_link"=>$this->lang->line("lastPage"),
			"last_tag_open"=>"<div class='firstPage'>",
			"last_tag_close"=>"</div>",
			"next_tag_open"=>"<div class='page'>",
			"next_tag_close"=>"</div>",
			"prev_tag_open"=>"<div class='page'>",
			"prev_tag_close"=>"</div>",
			"num_tag_open"=>"<div class='page'>",
			"num_tag_close"=>"</div>",
			'cur_tag_open'=>"<div class='currentPage'>",
			'cur_tag_close'=>"</div>"
		);
		$this->pagination->initialize($c);
		$this->data["pagination"] = $this->pagination->create_links();
	}
	
	
	
	
	/**
	 * @desc This will get called when a button in list pressed
	 * Form handler for lists
	 */
	function submitInventoryForm($modelName){
		if($this->input->post("backAfterSubmit"))
			setcookie("backAfterSubmit",$this->input->post("backAfterSubmit"));
		if($this->input->post('search')){
			$this->inventory($modelName);
		}elseif($this->input->post('remove')){
			$this->delete($modelName);
		}
	}
	
	
	
	/**
	 * @desc This will delete records of table
	 * @param Array $_POST 'ids' ids of records which should delete
	 */
	function delete($modelName){
		
		//loading model & language
		$this->load->model($modelName);
		$this->lang->load($this->$modelName->langFileName);
		
		
		if(!isset($this->$modelName->listControllerName))
			$this->$modelName->listControllerName = "home";
		
		
		// and as always these will get used in view file
		$this->data["moduleName"] = $this->$modelName->moduleName;
		$this->data["breadcrumb"][$this->lang->line($this->$modelName->moduleName)] = base_url()."cp/".$this->$modelName->listControllerName."/inventory/".$modelName;
		$this->data["breadcrumb"][$this->lang->line("delete")] = "";
		
		$accessLevelRecs = $this->accessLevelModel->getRecords(array("module_name"=>$this->$modelName->moduleName."Module","category_id"=>$this->session->userdata["category_id"]));
		
		if(count($accessLevelRecs) > 0)$accessLevel = $accessLevelRecs[0];
		else $accessLevel = null;
		
		if(count($accessLevelRecs) < 1 || !$accessLevel->perm_delete){
			
			$this->data["errors"][] = $this->lang->line("no-perm");
			$this->data["content"] = $this->load->view("cp/messages",$this->data,TRUE);
			$this->load->view('cp/container',$this->data);
		
		}else{
		
			// check to see if any thing selected 
			if($this->input->post('ids')){
				$ids = array_keys($this->input->post('ids'));
				if($this->$modelName->delete($ids)){
					$this->data["messages"][] = $this->lang->line("deleted");
				}else{
					$this->data["errors"][] = $this->lang->line("noPermissionToDelete");
				}
			}else{
				$this->data["errors"][] = $this->lang->line("noItemSelected");
			}
			
			// fire !! load the view
			$this->data["content"] = $this->load->view('cp/messages',$this->data, TRUE);
			$this->load->view('cp/container',$this->data);
			
		}
	}
	
	
	
	function formForLang($modelName,$lang,$languageRelation){
		$this->load->model($modelName);
		$items = $this->$modelName->getRecords(array("language_relation"=>$languageRelation,"language"=>$lang));
		if(count($items) > 0)
			$item = $items[0];
		if(isset($item) && is_object($item)){
			$id = $item->id;
		}else{
			$id = 0;
		}
		
		$defaultFields="";
		$defaultValues="";
		
		// loading language
		$this->lang->load($this->$modelName->langFileName);

		if(!isset($this->$modelName->listControllerName))
			$this->$modelName->listControllerName = "home";
		
		// these will be usefull in view
		$this->data["modelName"] = $modelName;
		$this->data["moduleName"] = $this->$modelName->moduleName;
		$this->data["breadcrumb"][$this->lang->line($this->$modelName->moduleName)] = base_url()."cp/".$this->$modelName->listControllerName."/inventory/".$modelName;
		if($id == 0){
			$this->data["breadcrumb"][$this->lang->line("add")] = "";
			$this->data["title"] .= " - ".$this->lang->line("add");
		}else{
			$this->data["breadcrumb"][$this->lang->line("edit")] = "";
			$this->data["title"] .= " - ".$this->lang->line("edit");
		}
		
		$accessLevelRecs = $this->accessLevelModel->getRecords(array("module_name"=>$this->$modelName->moduleName."Module","category_id"=>$this->session->userdata["category_id"]));
		
		if(count($accessLevelRecs) > 0)$accessLevel = $accessLevelRecs[0];
		else $accessLevel = null;
		
		if(count($accessLevelRecs) < 1 || ($id == 0 && !$accessLevel->perm_add) || ($id != 0 && !$accessLevel->perm_edit)){
			
			
			$this->data["errors"][] = $this->lang->line("no-perm");
			$this->data["content"] = $this->load->view("cp/messages",$this->data,TRUE);
		
		}else{
			
			// check to see if this should be a empty form or not
			if($id != 0){
				$this->data["item"] = $item;
			}else{
				$this->data["item"]->language = $lang;
				$this->data["item"]->language_relation = $languageRelation;
				
			}
			
			// preparing form fields from model 'formFields'
			$fields = $this->$modelName->formFields;
			$this->data["validation"] = false;
			$this->data["xinha"] = false;
			$this->data["calendar"] = false;
			foreach($fields as $field=>$specification){
				if(isset($specification["mandatory"])){
					$this->data["validation"] = true;
				}
				if($specification["type"] == "xinha"){
					$this->data["xinha"] = true;
				}
				if($specification["type"] == "timeSelector"){
					$this->data["calendar"] = $field;
				}
				if(($specification["type"] == "timeView" || $specification["type"] == "timeSelector") && isset($this->data["item"])){
					if(isset($this->data["item"]->$field) && $this->data["item"]->$field > 1){
						if(isset($this->data["item"]->language) && $this->data["item"]->language != "fa" || !isset($this->data["item"]->language)){
							$this->data["item"]->$field = date("Y-m-d H:i",$this->data["item"]->$field);
						}else{
							$this->load->helper("jdate");
							$this->data["item"]->$field = jdate("Y-m-d H:i",$this->data["item"]->$field);
						}
					}else{
						$this->data["item"]->$field = "";
					}
				}
				if($specification["type"] == "select"){
					$fields[$field]["options"] = array();
					if(isset($specification["source"]["modelName"])){
						$sourceModelName = $specification["source"]["modelName"];
						$titleField = $specification["source"]["titleField"];
						$valueField = $specification["source"]["valueField"];
						$this->load->model($sourceModelName);
						$recs = $this->$sourceModelName->getRecords();
						foreach($recs as $rec){
							$fields[$field]["options"][$rec->$valueField] = $rec->$titleField;
						}
					}else{
						foreach($specification["source"] as $value=>$langName){
							$fields[$field]["options"][$value] = $this->lang->line($langName);
						}
					}
				}
				if($specification["type"] == "upload" && isset($this->data["item"]) && $this->data["item"]->$field != ""){
					$fileNameParts = explode(".",$this->data["item"]->$field);
					if($fileNameParts[1] == "jpg" || $fileNameParts[1] == "png" || $fileNameParts[1] == "gif"){
						$this->load->helper("simple_image");
						$si = new SimpleImage();
						$this->data["item"]->$field = array(
							"type"=>"image",
							"path"=>$si->getThumbPathWidthHeight($this->data["item"]->$field,0,100)
						);
					}else{
						$this->data["item"]->$field = array(
							"type"=>"other",
							"path"=>base_url()."files/uploaded/".$this->data["item"]->$field
						);
					}
				}
				if($specification["type"] == "categorySelect"){
					$sourceModelName = "categoriesModel";
					$titleField = "title";
					$valueField = "id";
					
					$this->load->model($sourceModelName);
					$parentRecord = $this->$sourceModelName->getRecordByInternalName($specification["internalName"]);
					$recs = $this->$sourceModelName->getAllChildren($parentRecord);
					
					$fields[$field]["options"] = array();
					if($recs)foreach($recs as $rec){
						$langRecord = $this->$sourceModelName->getLangRecord($rec->id,$lang);
						if(isset($specification["noMainBranches"]) && $rec->children > 0){
							$fields[$field]["options"][$langRecord->$titleField] = (isset($langRecord->$titleField))?$langRecord->$titleField:"";
						}else{
							$fields[$field]["options"][$rec->$valueField] = (isset($langRecord->$titleField))?$langRecord->$titleField:"";
						}
					}
				}
			}
			$this->data["fields"] = $fields;
			
			
			$this->data["defaultFields"] = explode("-",$defaultFields);
			$this->data["defaultValues"] = explode("-",$defaultValues);
			
			$this->data["content"] = $this->load->view("cp/form",$this->data,TRUE);
			
		}
		
		// loading the view
		// check to see if the request is ajax based or not
		if($this->input->is_ajax_request()){
			$i=0;
			$breadCrumb = "";
			foreach($this->data["breadcrumb"] as $bread=>$crumb){
				if(++$i > 1) $breadCrumb .= "&nbsp;&raquo;&nbsp;";
				if($crumb != ""){
					$breadCrumb .= "<a href=".$crumb." onclick=\"one.changeContent(this.href); return false;\">";
				}
				$breadCrumb .= $bread;
				if($crumb != ""){
					$breadCrumb .= "</a>";
				}
			}
			$json = "{";
			$json .= "breadCrumb:'".$breadCrumb."',";
			if(isset($this->data["validation"]))$json .= "validation:'".$this->data["validation"]."',";
			if(isset($this->data["xinha"]))$json .= "xinha:'".$this->data["xinha"]."',";
			if(isset($this->data["calendar"]))$json .= "calendar:'".$this->data["calendar"]."',";
			$json .= "title:'".$this->data["title"]."'";
			$json .= "}";
			echo $json."|-|".$this->data["content"];
		}else{
			$this->load->view('cp/container',$this->data);
		}
		
	}
	
	
	
	
	/**
	 * @desc This method will show a form to add or edit items
	 * @param modelName
	 * @param id is the id field of the record to edit
	 * @param $defaultFields fileds that have default value in the form
	 * @param $defaultValues values of the default fields 
	 */
	function form($modelName,$id=0,$defaultFields="",$defaultValues=""){

		// loading model & language
		$this->load->model($modelName);
		$this->lang->load($this->$modelName->langFileName);
		
		$this->load->helper("form");

		if(!isset($this->$modelName->listControllerName))
			$this->$modelName->listControllerName = "home";
		
		// these will be usefull in view
		$this->data["modelName"] = $modelName;
		$this->data["moduleName"] = $this->$modelName->moduleName;
		$this->data["breadcrumb"][$this->lang->line($this->$modelName->moduleName)] = base_url()."cp/".$this->$modelName->listControllerName."/inventory/".$modelName;
		if($id == 0){
			$this->data["breadcrumb"][$this->lang->line("add")] = "";
			$this->data["title"] .= " - ".$this->lang->line("add");
		}else{
			$this->data["breadcrumb"][$this->lang->line("edit")] = "";
			$this->data["title"] .= " - ".$this->lang->line("edit");
		}
		
		$accessLevelRecs = $this->accessLevelModel->getRecords(array("module_name"=>$this->$modelName->moduleName."Module","category_id"=>$this->session->userdata["category_id"]));
		
		if(count($accessLevelRecs) > 0)$accessLevel = $accessLevelRecs[0];
		else $accessLevel = null;
		
		if(count($accessLevelRecs) < 1 || ($id == 0 && !$accessLevel->perm_add) || ($id != 0 && !$accessLevel->perm_edit)){
			
			
			$this->data["errors"][] = $this->lang->line("no-perm");
			$this->data["content"] = $this->load->view("cp/messages",$this->data,TRUE);
		
		}else{
			
				
			// check to see if this should be a empty form or not
			if($id != 0){
				$this->data["item"] = $this->$modelName->getRecord("id",$id);
			}
			
			// preparing form fields from model 'formFields'
			$fields = $this->$modelName->formFields;
			$this->data["validation"] = false;
			$this->data["xinha"] = false;
			$this->data["calendar"] = false;
			foreach($fields as $field=>$specification){
				if(isset($specification["mandatory"])){
					$this->data["validation"] = true;
				}
				if($specification["type"] == "xinha"){
					$this->data["xinha"] = true;
				}
				if($specification["type"] == "timeSelector"){
					$this->data["calendar"] = $field;
				}
				if(($specification["type"] == "timeView" || $specification["type"] == "timeSelector") && isset($this->data["item"])){
					if($this->data["item"]->$field > 1){
						if(isset($this->data["item"]->language) && $this->data["item"]->language != "fa" || !isset($this->data["item"]->language)){
							$this->data["item"]->$field = @date("Y-m-d H:i",$this->data["item"]->$field);
						}else{
							$this->load->helper("jdate");
							$this->data["item"]->$field = jdate("Y-m-d H:i",$this->data["item"]->$field);
						}
					}else{
						$this->data["item"]->$field = "";
					}
				}
				if($specification["type"] == "select"){
					$fields[$field]["options"] = array();
					if(isset($specification["source"]["modelName"])){
						$sourceModelName = $specification["source"]["modelName"];
						$titleField = $specification["source"]["titleField"];
						$valueField = $specification["source"]["valueField"];
						$this->load->model($sourceModelName);
						$recs = $this->$sourceModelName->getRecords();
						foreach($recs as $rec){
							$fields[$field]["options"][$rec->$valueField] = $rec->$titleField;
						}
					}else{
						foreach($specification["source"] as $value=>$langName){
							$fields[$field]["options"][$value] = $this->lang->line($langName);
						}
					}
				}
				if($specification["type"] == "upload" && isset($this->data["item"]) && $this->data["item"]->$field != ""){
					$fileNameParts = explode(".",$this->data["item"]->$field);
					if(strtolower($fileNameParts[1]) == "jpg" || strtolower($fileNameParts[1]) == "png" || strtolower($fileNameParts[1]) == "gif"){
						$this->load->helper("simple_image");
						$si = new SimpleImage();
						$this->data["item"]->$field = array(
							"type"=>"image",
							"path"=>$si->getThumbPathWidthHeight($this->data["item"]->$field,0,100)
						);
					}else{
						$this->data["item"]->$field = array(
							"type"=>"other",
							"path"=>base_url()."files/uploaded/".$this->data["item"]->$field
						);
					}
				}
				if($specification["type"] == "categorySelect"){
					$sourceModelName = "categoriesModel";
					$titleField = "title";
					$valueField = "id";
					
					$this->load->model($sourceModelName);
					$parentRecord = $this->$sourceModelName->getRecordByInternalName($specification["internalName"]);
					$recs = $this->$sourceModelName->getAllChildren($parentRecord);
					
					$fields[$field]["options"] = array();
					if($id != 0 && isset($this->data["item"]->language)){
						$l = $this->data["item"]->language;
					}else{
						$l = "en";
					}
					
					if($recs)foreach($recs as $rec){
						
						$langRecord = $this->$sourceModelName->getLangRecord($rec->id,$l);
						if(isset($specification["noMainBranches"]) && $rec->children > 0){
							$fields[$field]["options"][$langRecord->$titleField] = $langRecord->$titleField;
						}else{
							$fields[$field]["options"][$rec->$valueField] = $langRecord->$titleField;
						}
						
					}
				}
			}
			$this->data["fields"] = $fields;
			
			
			$this->data["defaultFields"] = explode("-",$defaultFields);
			$this->data["defaultValues"] = explode("-",$defaultValues);
			
			$this->data["content"] = $this->load->view("cp/form",$this->data,TRUE);
			
		}
		
		// loading the view
		// check to see if the request is ajax based or not
		if($this->input->is_ajax_request()){
			$i=0;
			$breadCrumb = "";
			foreach($this->data["breadcrumb"] as $bread=>$crumb){
				if(++$i > 1) $breadCrumb .= "&nbsp;&raquo;&nbsp;";
				if($crumb != ""){
					$breadCrumb .= "<a href=".$crumb." onclick=\"one.changeContent(this.href); return false;\">";
				}
				$breadCrumb .= $bread;
				if($crumb != ""){
					$breadCrumb .= "</a>";
				}
			}
			$json = "{";
			$json .= "breadCrumb:'".$breadCrumb."',";
			if(isset($this->data["validation"]))$json .= "validation:'".$this->data["validation"]."',";
			if(isset($this->data["xinha"]))$json .= "xinha:'".$this->data["xinha"]."',";
			if(isset($this->data["calendar"]))$json .= "calendar:'".$this->data["calendar"]."',";
			$json .= "title:'".$this->data["title"]."'";
			$json .= "}";
			echo $json."|-|".$this->data["content"];
		}else{
			$this->load->view('cp/container',$this->data);
		}
	}
	
	
	
	
	
	/**
	 * @desc This the form handler fot getForm method
	 * @param String what - add or edit
	 * @param Integer id - id of the editable record
	 */
	function submitForm($modelName,$what,$id=0){
		if($this->input->is_ajax_request()){
			$this->inventory($modelName);
		}else{
		
			if($this->input->post("backAfterSubmit"))
				setcookie("backAfterSubmit",$this->input->post("backAfterSubmit"));
			
			// loading model & language
			$this->load->model($modelName);
			$this->lang->load($this->$modelName->langFileName);
			
			$fields = $this->$modelName->formFields;
			
			// preparing insertable array of fields values
			$fieldsValues = array();
			foreach($fields as $field=>$specifications){
				if($specifications["type"] == "timeSelector" && $this->input->post($field) > 1){
					$dateTime = explode(" ",$this->input->post($field));
					$dateParts = explode("-",$dateTime[0]);
					$timeParts = explode(":",$dateTime[1]);
					
					if($dateParts[0] < 1500){
						$this->load->helper("jdate");
						$fieldsValues[$field] = @jmaketime($timeParts[0],$timeParts[1],0,$dateParts[1],$dateParts[2],$dateParts[0]);
					}else{
						$fieldsValues[$field] = @mktime($timeParts[0],$timeParts[1],0,$dateParts[1],$dateParts[2],$dateParts[0]);
					}
				}elseif($specifications["type"] == "password"){
					
					if($this->input->post($field) != ""){
						$fieldsValues[$field] = md5($this->input->post($field));
					}else{
						unset($fieldsValues[$field]);
					}
					
				}elseif($specifications["type"] == "timeView"){
					
					unset($fieldsValues[$field]);
					
				}elseif($specifications["type"] == "upload"){
					
					if($_FILES[$field]["name"] != ""){
						if($_FILES[$field]["error"] == "0" && is_uploaded_file($_FILES[$field]['tmp_name'])){
							$nameParts = explode(".",$_FILES[$field]["name"]);
							$filename = md5(microtime()).".".$nameParts[1];
							move_uploaded_file($_FILES[$field]['tmp_name'],"files/uploaded/".$filename);
							$fieldsValues[$field] = $filename;
						}else{
							$this->data["errors"][] = "'".$field."' File not uploaded.";
						}
						
					}
					
				}else{
					$fieldsValues[$field] = $this->input->post($field);
				}
			}
			
			if(!isset($this->$modelName->listControllerName))
				$this->$modelName->listControllerName = "home";
			
			// these will be usefull in view
			$this->data["moduleName"] = $this->$modelName->moduleName;
			$this->data["breadcrumb"][$this->lang->line($this->$modelName->moduleName)] = base_url()."cp/".$this->$modelName->listControllerName."/inventory/".$modelName;
			
			if(!isset($this->data["errors"])){
				
				if($what == "add" && $id == 0){
					
					// check to see if this record is already exist
					$recs = $this->$modelName->getRecords($fieldsValues,0,1);
					if(count($recs) > 0){
						$this->data["errors"][] = $this->lang->line("alreadyExist");
					}else{
						if($this->$modelName->insert($fieldsValues)){
							$this->data["messages"][] = $this->lang->line("added");
						}else{
							$this->data["errors"][] = $this->lang->line("alreadyExist");
						}
						$this->data["breadcrumb"][$this->lang->line("add")] = "";
						$this->data["title"] .= " - ".$this->lang->line("add");
					}
				}else{
					if($this->$modelName->update($id,$fieldsValues)){
						$this->data["messages"][] = $this->lang->line("edited");
					}else{
						$this->data["errors"][] = $this->lang->line("noPermissionToUpdate");
					}
					$this->data["breadcrumb"][$this->lang->line("edit")] = "";
					$this->data["title"] .= " - ".$this->lang->line("edit");
				}
			}
			
			//loading the view
			$this->data["content"] = $this->load->view('cp/messages',$this->data, TRUE);
			$this->load->view('cp/container',$this->data);
		}
	}
	
	
}